package com.htc.dlc.fragment;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;

import com.htc.adapter.EventsModelAdapter;
import com.htc.calendar.CalendarAdapter;
import com.htc.common.ActionEvent;
import com.htc.constants.Constants;
import com.htc.controller.EventsController;
import com.htc.dlc.DetailEventActivity;
import com.htc.dlc.R;
import com.htc.dlc.SettingsActivity;
import com.htc.model.dto.EventsDTO;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class FragmentEvent extends Fragment implements OnItemClickListener {
	public GregorianCalendar month, itemmonth;// calendar instances.
	public CalendarAdapter adapter;// adapter instance
	public Handler handler;// for grabbing some event values for showing the dot
							// marker.
	public ArrayList<String> items; // container to store calendar items which
									// needs showing the event marker
	TextView tv_actionbar_title;
	ArrayList<Object> arrData;
	ListView list_event_calendar;
	EventsModelAdapter events_adapter;
	ArrayList<Object> events_array_data;
	View cacularView;
	View footer;
	GridView gridview;
	TextView inform_events_txt;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_event, container,
				false);
		list_event_calendar = (ListView) rootView
				.findViewById(R.id.list_event_calendar);

		cacularView = getActivity().getLayoutInflater().inflate(
				R.layout.activity_calendar, null);

		footer = getActivity().getLayoutInflater().inflate(
				R.layout.activity_footer, null);
		list_event_calendar.addHeaderView(cacularView);
		list_event_calendar.addFooterView(footer);

		// this.tv_actionbar_title = (TextView)
		// findViewById(R.id.tv_actionbar_title);
		// this.tv_actionbar_title.setText("Events");
		return rootView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		arrData = new ArrayList<Object>();
		events_array_data = new ArrayList<Object>();
		events_adapter = new EventsModelAdapter(getActivity(),
				R.layout.adapter_events, events_array_data);
		list_event_calendar.setAdapter(events_adapter);
		initData1();
		this.list_event_calendar.setOnItemClickListener(this);
		initCalendar();
	}

	private void initData1() {

		ActionEvent e = new ActionEvent(this, Constants.GET_EVENTS, null, null);
		EventsController.getInstance().handleViewEvent(e);
	}

	@SuppressWarnings("unchecked")
	public void handleControllerViewEvent(ActionEvent e) {
		switch (e.action) {
		case Constants.GET_EVENTS:
			ArrayList<EventsDTO> newArr = (ArrayList<EventsDTO>) e.viewData;
			new VerySlowTask(newArr).execute();
			break;
		default:
			break;
		}
	}

	public class VerySlowTask extends AsyncTask<String, Object, Void> {
		List<EventsDTO> _newArr;

		public VerySlowTask(List<EventsDTO> arr) {
			_newArr = arr;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(String... params) {
			try {
				for (int i = 0; i < _newArr.size(); i++) {
					publishProgress(_newArr.get(i));

				}
			} catch (Exception e) {
				// TODO: handle exception
			}

			return null;
		}

		@Override
		protected void onProgressUpdate(Object... values) {
			arrData.add(values[0]);

		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			events_adapter.notifyDataSetChanged();
			adapter.notifyDataSetChanged();
		}

	}

	private void initCalendar() {
		month = (GregorianCalendar) GregorianCalendar.getInstance();
		itemmonth = (GregorianCalendar) month.clone();
		this.inform_events_txt = (TextView) cacularView
				.findViewById(R.id.inform_events_txt);
		items = new ArrayList<String>();
		adapter = new CalendarAdapter(getActivity(), month, events_array_data);

		gridview = (GridView) cacularView.findViewById(R.id.gridview);
		gridview.setAdapter(adapter);

		handler = new Handler();
		handler.post(calendarUpdater);

		TextView title = (TextView) cacularView.findViewById(R.id.title);
		title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));

		RelativeLayout previous = (RelativeLayout) cacularView
				.findViewById(R.id.previous);

		previous.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setPreviousMonth();
				refreshCalendar();
				UpdateListView();
			}
		});

		RelativeLayout next = (RelativeLayout) cacularView
				.findViewById(R.id.next);
		next.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setNextMonth();
				refreshCalendar();
				UpdateListView();
			}
		});

		gridview.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {

				((CalendarAdapter) parent.getAdapter()).setSelected(v);
				String selectedGridDate = CalendarAdapter.dayString
						.get(position);
				// separatedTime return arrays year, month, day.
				String[] separatedTime = selectedGridDate.split("-");

				String gridvalueString = separatedTime[2].replaceFirst("^0*",
						"");// taking last part of date. ie; 2 from 2012-12-02.
				int gridvalue = Integer.parseInt(gridvalueString);
				// navigate to next or previous month on clicking offdays.
				if ((gridvalue > 10) && (position < 8)) {
					setPreviousMonth();
					refreshCalendar();
				} else if ((gridvalue < 7) && (position > 28)) {
					setNextMonth();
					refreshCalendar();
				}
				// ((CalendarAdapter) parent.getAdapter()).setSelected(v);

			}
		});
	}

	protected void UpdateListView() {
		this.events_array_data.clear();
		List<String> dayString = CalendarAdapter.dayString;
		for (int i = 0; i < dayString.size(); i++) {
			String currentDate = dayString.get(i);
			for (int j = 0; j < arrData.size(); j++) {
				EventsDTO dto = (EventsDTO) arrData.get(j);
				if (dto.getEventDate().equals(currentDate)) {
					this.events_array_data.add(dto);
				}
			}
		}
		// update adapter
		this.events_adapter.notifyDataSetChanged();
		if (this.events_adapter.getCount() > 0) {
			this.inform_events_txt.setText("This Month's Events");
		} else {
			this.inform_events_txt.setText("No Events Found");
		}
	}

	protected void setNextMonth() {
		if (month.get(GregorianCalendar.MONTH) == month
				.getActualMaximum(GregorianCalendar.MONTH)) {
			month.set((month.get(GregorianCalendar.YEAR) + 1),
					month.getActualMinimum(GregorianCalendar.MONTH), 1);
		} else {
			month.set(GregorianCalendar.MONTH,
					month.get(GregorianCalendar.MONTH) + 1);
		}
	}

	protected void setPreviousMonth() {
		if (month.get(GregorianCalendar.MONTH) == month
				.getActualMinimum(GregorianCalendar.MONTH)) {
			month.set((month.get(GregorianCalendar.YEAR) - 1),
					month.getActualMaximum(GregorianCalendar.MONTH), 1);
		} else {
			month.set(GregorianCalendar.MONTH,
					month.get(GregorianCalendar.MONTH) - 1);
		}
	}

	public void refreshCalendar() {
		TextView title = (TextView) cacularView.findViewById(R.id.title);

		adapter.refreshDays();
		adapter.notifyDataSetChanged();
		handler.post(calendarUpdater); // generate some calendar items

		title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));
	}

	public Runnable calendarUpdater = new Runnable() {

		@Override
		public void run() {
			items.clear();

			// Print dates of the current week
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
			String itemvalue;
			for (int i = 0; i < 7; i++) {
				itemvalue = df.format(itemmonth.getTime());
				itemmonth.add(GregorianCalendar.DATE, 1);
				items.add("2012-09-12");
				items.add("2012-10-07");
				items.add("2012-10-15");
				items.add("2012-10-20");
				items.add("2012-11-30");
				items.add("2012-11-28");
			}

			adapter.setItems(items);
			adapter.notifyDataSetChanged();
		}
	};

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		
		if(events_adapter.getArrObject().size() >=1){
//			Object o = events_adapter.getArrObject().get(position - 1);
//			int i = 0;
			EventsDTO dto = null;
			try {
				dto = (EventsDTO)list_event_calendar.getItemAtPosition(position);
				Intent intent = new Intent(getActivity(), DetailEventActivity.class);
				Bundle data = new Bundle();

				SettingsActivity st = new SettingsActivity();
				if (st.flag == 0) {
					data.putString("title", dto.getEventTitle());
					data.putString("description", dto.getEventDescription());

				} else if (st.flag == 1) {
					data.putString("title", dto.getEventTitleAr());
					data.putString("description", dto.getEventDescriptionAr());
				}
				data.putString("image", dto.getEventImage());
				intent.putExtras(data);
				startActivity(intent);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		

	}
}
